local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"
require "ddzenum"
local table_insert = table.insert

local filelog = require "filelog"
local configdao = require "configdao"

local roles = {}
local Router = {
	idle_table_mng = nil,
}

function Router.forward(rid, tablesvr, table_index)
	roles[rid] = {
		tablesvr = tablesvr,
		idx = table_index,
	}
	cluster.send("gatenode", ".router", "role_enter_table", rid, skynet.getenv("nodename"), table_index)
end

function Router.unforward(rid, table_index)
	local idx
	if roles[rid] then
		idx = roles[rid].idx
		roles[rid] = nil
	else
		idx = table_index
	end
	cluster.send("gatenode", ".router", "role_leave_table", rid, skynet.getenv("nodename"), idx)
end

function Router.get_role_data(rid)
	return roles[rid]
end

function Router.get_table_allrid(idx)
	local rids = {}
	for rid, v in pairs(roles) do
		if v.idx == idx then
			table_insert(rids, rid)
		end
	end
	return rids
end

function Router.exit_service()
	skynet.exit()
end

local function add_events(name)
	local events = require(name)
	for fn, f in pairs(events) do
		if Router[fn] then
			error("duplicate function: name " .. tostring(fn))
		end
		if type(f) == 'function' then
			if fn == "init" then
				f(Router)
			else
				Router[fn] = f
			end
		end
	end
end

-- 这里主要负责处理向桌子发起的请求
local function table_request(cmd, rid, rdata, args)
	if cmd == "disconnect" then
		Router.cancelmatch(rid, rdata, args)
	end
	args = args or {}
	-- filelog.debug("request from gate agent: ", tostring(cmd))--, tostring(rid), args)
	if roles[rid] and roles[rid].tablesvr then
		if type(args) ~= type{} then
			filelog.sys_error("invalid args! ===>", cmd, args)
			return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "参数错误！"}
		end
		args.rid = rid
		args.playerinfo = rdata.info
		args.playerinfo.ip_addr = rdata.ip_addr
		args.playerinfo.gps_addr = rdata.gps_addr
		args.money = rdata.money
		local status, retmsg = pcall(skynet.call, roles[rid].tablesvr, "lua", cmd, args)
		-- filelog.debug("response to gate agent:")--, retmsg)
		if status then
			return retmsg
		else
			filelog.sys_error("call table server: " .. cmd .. " failed!", "msg: " .. (retmsg or "nil"))
			return {retcode = EErrCode.ERR_SYSTEM_ERROR, retstr = "系统错误！"}
		end
	else
		filelog.sys_error("role not in game table!", cmd)
		return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "玩家没在游戏中！"}
	end
end

local function init()
	add_events("nodecmd")
	add_events("matchroom")
	-- add_events("coinmatchroom")
	if Router['init_table_pool'] then
		Router['init_table_pool'](configdao.get_cfgsvrs_key(skynet.getenv("nodename")))
	end
end

local function test()
	-- local ddzlogic = require "ddzgamelogic_lz"
	-- local lztab = {13, 12}	-- 43 42 41 40, 39, 38, 37, 36
	-- local cards = {44,40,36,32,28,24}
	-- local cardHelper = ddzlogic.CreateCardsHelper(cards)
	-- cardHelper:GetCardsType(cardHelper, lztab)		--牌形识别
	-- -- filelog.debug("card type is: ", cardHelper.m_eCardType, cardHelper.m_keyMaxValue)

	local ddzlogic = require "ddzgamelogic"
	local table_data = {conf = {game_type = 1}}
	local count = {}
	local starttime = os.time()
	local robot = require "ddzrobot"
	for i = 1, 1 do
		----生成一副牌
		ddzlogic.InitCards(table_data)
		----洗牌
		ddzlogic.Riffle(table_data)
		table_data.seats = {{}, {}, {}}
		ddzlogic.PostCards(table_data, 1)
		local points = robot:calcardspoints(table_data.seats[1].cards)
		local n = points - points % 10
		count[n] = (count[n] or 0) + 1
		points = robot:calcardspoints(table_data.seats[2].cards)
		n = points - points % 10
		count[n] = (count[n] or 0) + 1
		points = robot:calcardspoints(table_data.seats[3].cards)
		n = points - points % 10
		count[n] = (count[n] or 0) + 1
		table_data.initCards = nil
	end
	filelog.debug("count = ", count)
	filelog.trace("usetime = ", os.time() - starttime)
end

skynet.start(function()
	skynet.dispatch("lua", function (session, source, cmd, ...)
		-- filelog.debug("received commamd: ", cmd, ...)
		local f = Router[cmd]
		if type(f) == 'function' then
			skynet.retpack(f(...))
		else
			skynet.retpack(table_request(cmd, ...))
		end
	end)
	init()

	-- test()
end)

